<template>
  <div>
    <!--验证码 生成-->
    <div>
      <h2>验证码</h2>
      <div>
        <img :src="captchaImg" @click="refreshCaptcha" alt=""/>
        <input type="text" v-model="userCaptcha"/>
        <button @click="verifyCaptcha">验证</button>
      </div>
      <p v-if="showMessage">{{ message }}</p>
    </div>
    <!-- 六十秒禁用 -->
<!--    <div>-->
<!--      <div>-->
<!--        <button @click="sendCode">发送验证码</button>-->
<!--        <span v-if="countdown > 0">{{ countdown }} 秒后重新获取</span>-->
<!--      </div>-->
<!--    </div>-->
<!-- 倒计时-->
    <div>
      <div>
        <button :disabled="isCountingDown" @click="sendCode">
          {{ isCountingDown? `${countdown} 秒后重新获取` : '发送验证码' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      countdown: 60,
      isCountingDown: false,
      // 倒计时
      // countdown: 0,
      captchaImg: '',
      userCaptcha: '',
      captchaText: '',
      showMessage: false,
      message: '',
    };
  },
  methods: {
    sendCode() {
      if (!this.isCountingDown) {
        // 发送验证码的逻辑
        this.isCountingDown = true;
        this.startCountdown();
      }
    },
    startCountdown() {
      const timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
          console.log(this.countdown--)
        } else {
          clearInterval(timer);
          this.isCountingDown = false;
          this.countdown = 60;
        }
      }, 1000);
    },
    // 倒计时
    // 验证码
    generateCaptcha() {
      const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
      let captcha = '';
      for (let i = 0; i < 4; i++) {
        captcha += letters.charAt(Math.floor(Math.random() * letters.length));
      }
      this.captchaText = captcha;

      const canvas = document.createElement('canvas');
      canvas.width = 150;
      canvas.height = 50;
      const ctx = canvas.getContext('2d');

      ctx.fillStyle = '#f0f0f0';
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      ctx.font = '25px Arial';
      ctx.fillStyle = '#000';

      for (let i = 0; i < captcha.length; i++) {
        ctx.save();
        const rotate = Math.random() * 30 - 15;
        ctx.rotate((rotate * Math.PI) / 180);
        ctx.fillText(captcha[i], 20 + i * 25, 30);
        ctx.restore();
      }
      this.captchaImg = canvas.toDataURL();
    },
    refreshCaptcha() {
      this.generateCaptcha();
      this.userCaptcha = '';
      this.showMessage = false;
    },
    verifyCaptcha() {
      if (this.userCaptcha.toLowerCase() === this.captchaText.toLowerCase()) {
        this.message = '验证成功';
        this.showMessage = true;
      } else {
        this.message = '验证失败，请重新输入';
        this.showMessage = true;
      }
    },
  },
  created() {
    this.generateCaptcha();
  },
};
</script>

<style scoped>
/* 可以添加样式来美化页面 */
</style>
